import { Inject, Injectable } from '@nestjs/common'
import { AUTH_OPTIONS } from '../auth.constants'
import { AuthModuleOptions } from '../interfaces/auth-options.interface'
import * as crypto from 'crypto'

@Injectable()
export class CryptographyService {
  private readonly encryptionSecretBuffer: Buffer
  private readonly encryptionSaltBuffer: Buffer

  constructor(@Inject(AUTH_OPTIONS) private readonly options: AuthModuleOptions) {
    this.encryptionSecretBuffer = Buffer.from(this.options.encryptionSecret, 'hex')
    this.encryptionSaltBuffer = Buffer.from(this.options.encryptionSalt, 'hex')
  }

  aesEncrypt(d: string) {
    const data = Buffer.from(d, 'utf8')
    const cipher = crypto.createCipheriv(
      'aes-256-cbc',
      this.encryptionSecretBuffer,
      this.encryptionSaltBuffer,
    )

    return Buffer.concat([ cipher.update(data), cipher.final() ]).toString('base64')
  }

  aesDecrypt(d: string) {
    const data = Buffer.from(d, 'base64')
    const decipher = crypto.createDecipheriv(
      'aes-256-cbc',
      this.encryptionSecretBuffer,
      this.encryptionSaltBuffer,
    )

    return Buffer.concat([ decipher.update(data), decipher.final() ]).toString('utf8')
  }
}
